<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Tuolaji <479923197@qq.com>
// +----------------------------------------------------------------------
namespace Portal\Controller;

use Common\Controller\AdminbaseController;

class AdminAboutController extends AdminbaseController
{

    protected $model;
    protected $terms_model;

    function _initialize()
    {
        parent::_initialize();
        $this->model = D("Portal/About");
        $this->terms_model = D("Portal/Terms");
    }

    public function index()
    {
        $cid = empty($_REQUEST['cid']) ? 0 : intval($_REQUEST['cid']);
        $category = get_one_category($cid);
        $this->assign('category', $category);
        $categoryList = $this->terms_model->where(array('parent' => 1))->select();
        $this->assign('categoryList', $categoryList);
        $action = "添加";
        if ($category['type'] == 1) {
            $where = array('cid' => $cid);
            $post = $this->model->where($where)->find();
            $template = 'add';
            $action = "";
            if (!empty($post)) {
                $template = 'edit';
                $this->assign('post', $post);
            }
        } else {
            $this->_lists(array("cid" => $cid, "status" => array('neq', 3)));
            $template = 'index';
        }
        $this->assign('action', $action);
        $this->display($template);
    }

    public function add()
    {
        $cid = empty($_REQUEST['cid']) ? 0 : intval($_REQUEST['cid']);
        $category = get_one_category($cid);
        $this->assign('category', $category);
        $this->assign('cid', $cid);
        $categoryList = $this->terms_model->where(array('parent' => 1))->select();
        $this->assign('categoryList', $categoryList);
        $action = '添加';
        $this->assign('action', $action);
        $this->display();
    }

    public function add_post()
    {
        if (IS_POST) {
            if (!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])) {
                foreach ($_POST['photos_url'] as $key => $url) {
                    $photourl = sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][] = array("url" => $photourl, "alt" => $_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['images'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['post']['updated_time'] = date("Y-m-d H:i:s", time());
            $_POST['post']['author'] = get_current_admin_id();
            $about = I("post.post");
            $about['smeta'] = json_encode($_POST['smeta']);
            $about['cid'] = intval($_POST['post']['cid']);
            $about['content'] = htmlspecialchars_decode($about['content']);
            $about['created_time'] = date("Y-m-d H:i:s", time());
            $about['m_content'] = htmlspecialchars_decode($about['m_content']);
            $about['file'] = intval($_POST['post']['file']);
            $result = $this->model->add($about);
            if ($result) {
                $this->success("添加成功！");
            } else {
                $this->error("添加失败！");
            }

        }
    }

    public function edit()
    {
        $cid = empty($_REQUEST['cid']) ? 0 : intval($_REQUEST['cid']);
        $category = get_one_category($cid);
        $this->assign('category', $category);
        $this->assign('cid', $cid);
        $id = intval(I("get.id"));
        $post = $this->model->where("id=$id")->find();
        $this->assign("post", $post);
        $this->assign("smeta", json_decode($post['smeta'], true));
        $action = '编辑';
        $this->assign('action', $action);
        $this->display();
    }

    //routes规则
    function updateUrlRule()
    {
        $list = $this->model->where('status =1')->order(array("id" => "asc"))->select();
        if (!empty($list)) {
            $urlRule = '';
            foreach ($list as $key => $item) {
                if (!empty($item['url_rule'])) {
                    $urlRule .= "	'" . str_replace('.html', '', $item['url_rule']) . "' =>'" . 'About/detail?id=' . $item['id'] . "',\r\n";
                    $data['url_rule'] = $item['url_rule'];
                } else {
                    $urlRule .= "	'about/" . $item['id'] . "' =>'" . 'About/detail?id=' . $item['id'] . "',\r\n";
                    $data['url_rule'] = 'about/' . $item['id'] . '.html';
                }
                $data['id'] = $item['id'];
                $this->model->save($data);
            }
            if (!empty($urlRule)) {
                $content = <<<EOT
<?php
return array(

EOT;
                $content .= $urlRule . ");";
                $filename = SITE_PATH . '/data/conf/about_route.php';
                file_put_contents($filename, $content);
            }
        }
    }

    public function edit_post()
    {
        if (IS_POST) {
            $urlRule = $_POST['post']['url_rule'];
            $id = $_POST['post']['id'];;
            $data = $this->model->where(array("id" => $id))->find();
            if (!empty($urlRule)) {
                $allUrlRule = getAllUrlRule();
                if ($data['url_rule'] != $urlRule && in_array($urlRule, $allUrlRule)) {
                    $this->error("修改失败，Url规则已存在！");
                }
            }
            $id = intval($_POST['post']['id']);

            if (!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])) {
                foreach ($_POST['photos_url'] as $key => $url) {
                    $photourl = sp_asset_relative_url($url);
                    $_POST['smeta']['photo'][] = array("url" => $photourl, "alt" => $_POST['photos_alt'][$key]);
                }
            }
            $_POST['smeta']['thumb'] = sp_asset_relative_url($_POST['smeta']['thumb']);
            $_POST['post']['updated_time'] = date("Y-m-d H:i:s", time());
            $about = I("post.post");
            $about['smeta'] = json_encode($_POST['smeta']);
            $about['cid'] = intval($_POST['post']['cid']);
            $about['content'] = htmlspecialchars_decode($about['content']);
            $about['m_content'] = htmlspecialchars_decode($about['m_content']);
            $result = $this->model->save($about);
            if ($result !== false) {
                $this->updateUrlRule();
                $this->success("保存成功！");
            } else {
                $this->error("保存失败！");
            }
        }
    }

    //排序
    public function listorders()
    {
        $status = $this->_listorders($this->model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }

    public function _listorders()
    {
        $ids = $_POST['listorders'];
        foreach ($ids as $key => $r) {
            $data['displayorder'] = $r;
            $this->model->where(array('id' => $key))->save($data);
        }
        return true;
    }

    private function _lists($where = array())
    {
        $term_id = I('request.term', 0, 'intval');

        if (!empty($term_id)) {
            $term = $this->terms_model->where(array('term_id' => $term_id))->find();
            $this->assign("term", $term);
        }

        $start_time = I('request.start_time');
        if (!empty($start_time)) {
            $where['created_time'] = array(
                array('EGT', $start_time)
            );
        }

        $end_time = I('request.end_time');
        if (!empty($end_time)) {
            if (empty($where['created_time'])) {
                $where['created_time'] = array();
            }
            array_push($where['created_time'], array('ELT', $end_time));
        }

        $keyword = I('request.keyword');
        if (!empty($keyword)) {
            $where['title'] = array('like', "%$keyword%");
        }

        $this->model
            ->where($where);
        $count = $this->model->count();

        $page = $this->page($count, 20);

        $this->model
            ->where($where)
            ->limit($page->firstRow, $page->listRows)
            ->order("displayorder desc,created_time DESC");
        $product = $this->model->select();

        $this->assign("page", $page->show('Admin'));
        $this->assign("formget", array_merge($_GET, $_POST));
        $this->assign("product", $product);
    }

    public function delete()
    {
        if (isset($_GET['id'])) {
            $id = I("get.id", 0, 'intval');
            if ($this->model->where(array('id' => $id))->delete() !== false) {
                $this->updateUrlRule();
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }

        if (isset($_POST['ids'])) {
            $ids = I('post.ids/a');

            if ($this->model->where(array('id' => array('in', $ids)))->delete() !== false) {
                $this->updateUrlRule();
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }

    function recommend()
    {
        if (isset($_POST['ids']) && $_GET["recommend"]) {
            $ids = I('post.ids/a');

            if ($this->model->where(array('id' => array('in', $ids)))->save(array('recommended' => 1)) !== false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if (isset($_POST['ids']) && $_GET["unrecommend"]) {
            $ids = I('post.ids/a');

            if ($this->model->where(array('id' => array('in', $ids)))->save(array('recommended' => 0)) !== false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }

    function recyclebin()
    {
        $this->_lists(array('status' => array('eq', 3)));
        $this->_getTree();
        $this->display();
    }

    function clean()
    {
        if (isset($_POST['ids'])) {
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status = $this->model->where(array("id" => array('in', $ids), 'status' => 3))->delete();

            if ($status !== false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        } else {
            if (isset($_GET['id'])) {
                $id = I("get.id", 0, 'intval');
                $status = $this->model->where(array("id" => $id, 'status' => 3))->delete();

                if ($status !== false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }

    function restore()
    {
        if (isset($_GET['id'])) {
            $id = I("get.id", 0, 'intval');
            if ($this->model->where(array("id" => $id, 'status' => 3))->save(array("status" => "1"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }

    function clearA()
    {
        $content = htmlspecialchars_decode(I("post.content"));
        preg_match_all("/\<a (.*?)>(.*?)\<\/a\>/is", $content, $aArr);
        if (!empty($aArr[0]) && $aArr[2]) $content = str_replace($aArr[0], $aArr[2], $content);
        $data['content'] = $content;
        preg_match_all('/<img[\s\S]*?src\s*=\s*[\\" | \'](.*?)[\\"|\'][\s\S]*?>/is', $content, $imgArr);
        //print_r($imgArr);
        echo json_encode($data);
    }

}